from alipay import Alipay


class AlipayTool():
    def __init__(self):
        with open("./keys/alipay_public_key.txt", "r", encoding="utf-8") as f:
            # 公钥
            alipay_public_key = f.read()
            f.close()

        with open("./keys/private_key.txt", "r", encoding="utf-8") as f:
            # 私钥
            private_key = f.read()
            f.close()

        # 2. 实例化阿里的SDK
        self.alipay = Alipay(
            appid="2021000121639206",  # APPID 从 open.alipay.com 获取
            app_private_key_string=private_key,  # 使用密钥生成工具生成的
            alipay_public_key_string=alipay_public_key,  # 用我们自己生成的公钥，与支付宝官方换来的支付宝的公钥
            debug=True,  # 调试模式打开
        )

    def create_order(self, title, price, order_num):
        url = self.alipay.api_alipay_trade_page_pay(  # 此方法是用来网页支付的
            subject=title,  # 订单标题
            out_trade_no=order_num,  # 我们自己平台的订单号
            total_amount=str(price),  # 支付金额，字符串形式。精确到两位小数
            return_url="http://127.0.0.1:8000/customer/paynotify/",  # 同步回调地址
            notify_url="https://www.baidu.com/",  # 异步回调地址,没有上线做不了，等上线后再说
        )

        url = "https://openapi.alipaydev.com/gateway.do?" + url

        return url